package ma.cdm.compteRendu.dao;
// default package


import static org.hibernate.criterion.Example.create;

import java.util.List;

import ma.cdm.compteRendu.bo.Comite;

import org.hibernate.Criteria;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;

/**
 	* A data access object (DAO) providing persistence and search support for Comite entities.
 			* Transaction control of the save(), update() and delete() operations 
		can directly support Spring container-managed transactions or they can be augmented	to handle user-managed Spring transactions. 
		Each of these methods provides additional information for how to configure it for the desired type of transaction control. 	
	 * @see .Comite
  * @author Limouri Anouar 
 */
    @Transactional   
public class ComiteDAO  {
	     private static final Logger log = LoggerFactory.getLogger(ComiteDAO.class);
		//property constants
	public static final String LIBELLECOMITE = "libellecomite";
	public static final String DESCRIPTIONCOMITE = "descriptioncomite";


	public void cleanComiteMembres(Long comiteId)
	{
		String hql = "delete from PersonneRole where comite.idcomite= :comiteId";
		getCurrentSession().createQuery(hql).setLong("comiteId", comiteId).executeUpdate();
	}
	

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory){
       this.sessionFactory = sessionFactory;
    }

    private Session getCurrentSession(){
     return sessionFactory.getCurrentSession(); 
    }
	protected void initDao() {
		//do nothing
	}
    
    public void save(Comite transientInstance) {
        log.debug("saving Comite instance");
        try {
            getCurrentSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
	public void delete(Comite persistentInstance) {
        log.debug("deleting Comite instance");
        try {
            getCurrentSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    public Comite findById( java.lang.Long id) {
        log.debug("getting Comite instance with id: " + id);
        try {
            Comite instance = (Comite) getCurrentSession()
                    .get(Comite.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    
    @SuppressWarnings("unchecked")
	public List<Comite> findByExample(Comite instance) {
        log.debug("finding Comite instance by example");
        try {
            List<Comite> results = (List<Comite>) getCurrentSession() .createCriteria(Comite.class).add( create(instance) ).list();
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Comite> getUserComite(String userId)
    {
    	log.debug("finding all user comites  instance by user  id");
        try {  
        	Criteria criteria = getCurrentSession().createCriteria(Comite.class);
        	criteria.createAlias("personneroles","personneRole");
        	criteria.createAlias("personneRole.membreComite","personne");
            criteria.add(Restrictions.eq("personne.matricule", userId));
            List results = criteria.list();         
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }
    @SuppressWarnings("rawtypes")
	public List findByProperty(String propertyName, Object value) {
      log.debug("finding Comite instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from Comite as model where model." 
         						+ propertyName + "= ?";
         Query queryObject = getCurrentSession().createQuery(queryString);
		 queryObject.setParameter(0, value);
		 return queryObject.list();
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	@SuppressWarnings("unchecked")
	public List<Comite> findByLibellecomite(Object libellecomite
	) {
		return findByProperty(LIBELLECOMITE, libellecomite
		);
	}
	
	@SuppressWarnings("unchecked")
	public List<Comite> findByDescriptioncomite(Object descriptioncomite
	) {
		return findByProperty(DESCRIPTIONCOMITE, descriptioncomite
		);
	}
	

	@SuppressWarnings("rawtypes")
	public List findAll() {
		log.debug("finding all Comite instances");
		try {
			String queryString = "from Comite";
	         Query queryObject = getCurrentSession().createQuery(queryString);
			 return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
    public Comite merge(Comite detachedInstance) {
        log.debug("merging Comite instance");
        try {
            Comite result = (Comite) getCurrentSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Comite instance) {
        log.debug("attaching dirty Comite instance");
        try {
            getCurrentSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(Comite instance) {
        log.debug("attaching clean Comite instance");
        try {
                      	getCurrentSession().buildLockRequest(LockOptions.NONE).lock(instance);
          	            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

	public static ComiteDAO getFromApplicationContext(ApplicationContext ctx) {
    	return (ComiteDAO) ctx.getBean("comiteDAO");
	}
}